import scrapy
import requests
from bid.items import BidItem
from bid.tools import *


class ShanghaiSpider(scrapy.Spider):
    name = 'shanghai'
    allowed_domains = ['www.shggzy.com']
    start_urls = ['http://www.shggzy.com/']
    t_lis = [
        ['https://www.shggzy.com/queryContent_%s-jyxx.jspx?channelId=30', '工程建设-资质预审公告','2'],
        ['https://www.shggzy.com/queryContent_%s-jyxx.jspx?channelId=29', '工程建设-招标公告','1'],
        ['https://www.shggzy.com/queryContent_%s-jyxx.jspx?channelId=32', '工程建设-中标候选人公示','2'],
        ['https://www.shggzy.com/queryContent_%s-jyxx.jspx?channelId=33', '工程建设-中标结果公示','3'],
        ['https://www.shggzy.com/queryContent_%s-jyxx.jspx?channelId=36', '政府采购-采购项目','1'],
        ['https://www.shggzy.com/queryContent_%s-jyxx.jspx?channelId=37', '政府采购-采购公告','1'],
        ['https://www.shggzy.com/queryContent_%s-jyxx.jspx?channelId=38', '政府采购-中标结果公告','3'],
        ['https://www.shggzy.com/queryContent_%s-jyxx.jspx?channelId=39', '政府采购-采购合同公告','3'],
    ]
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.81 Safari/537.36'}
    msg=[]
    def start_requests(self):
        for lis in self.t_lis:
            for page in range(1, 9999):
                res = requests.get(lis[0] % page, headers=self.headers)
                ls = re.findall('<li onclick="window.open\(\'(.*?)\'\)".*?class="cs-span2".*?>\s*(.*?)\s*<.*?<span style.*?<span>(.*?)</span>\s*</li>', res.text, re.S)
                last_page = re.findall('\s,count: (\d+)\s', res.text, re.S)[0]
                if page > int(last_page)//10+1:
                    break
                for l in ls:
                    item = {}
                    item['link'] = l[0]
                    item['title'] = l[1]
                    item['time'] = l[2]
                    item['classification'] = '上海-'+lis[1]
                    item['typ'] = lis[-1]
                    if redis_dupefilter(item) or item['time'].startswith('2021'):
                        self.msg.append(lis)
                        break
                    yield scrapy.Request(url=item['link'], callback=self.parse, meta={'item': item})
                if lis in self.msg:
                    print(lis[1],'完成')
                    break
                time.sleep(len(ls))

    def parse(self, response):
        item = BidItem()
        item.update(response.meta['item'])
        item['content'] = get_content(response.text, '//div[@class="content"]')
        item = get_field(dict(item))
        yield item
